﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace XMLParser
{
    class Writer
    {
        private ClassObject _root;

        public Writer( ClassObject root )
        {
            _root = root;
        }

        // CATIDOMNodeList_var spListNode ;
        // hr = GetChildNodes(spListNode) 
        public void Stream( String strXMLFile, String parentDir, String buffer )
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlElement rootElem =  xmlDoc.CreateElement( _root._Tag );

            xmlDoc.AppendChild( rootElem );

            _root.WriteXML( xmlDoc, rootElem );

            strXMLFile += "-output.xml";
            xmlDoc.Save( strXMLFile );

            System.Console.WriteLine( "Saved output to {0}", strXMLFile );

            // create a Stream writer and open the file
            String strFilePath = parentDir + "\\" + "Writer.cxx";

            TextWriter tw = new StreamWriter( strFilePath );

            String strContent = "<#assign xml = " + ClassObject.Box( _root._Name ) + "?cap_first >";
            tw.WriteLine( strContent );

            tw.WriteLine( buffer );

            String strCode = _root.GenerateWriterCode( parentDir );

            strContent = "\nHRESULT ${className}::Write(CATUnicodeString & iXMLFile, ${baseName}" + _root._Name + " *& op" + _root._Name + ")  ";
            strContent += "\n{";
            strContent += "\nHRESULT hr = E_FAIL ; ";
            strContent += "\nCATIDOMElement_var spRoot; ";
            strContent += "\nhr = Write" + _root._Name + "( spRoot, op" + _root._Name + " ) ; ";
            strContent += @"
            if( FAILED(hr) ) 
            { 
                return hr;                
            } ";

            tw.WriteLine( strContent );

            tw.WriteLine( "\nreturn hr;" );
            tw.WriteLine( "}" );

            tw.WriteLine( strCode );

            // close the stream
            tw.Close();

        }

    }
}
